package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.GlobalExceptionHandler;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.dto.ApUserPageRequestDto;
import com.itheima.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.mapper.ApUserRealnameMapper;
import com.itheima.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.events.Event;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>APP实名认证信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApAuthorFeign apauthorFeign;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public PageResultVo<ApUserRealname> pageList(ApUserPageRequestDto dto) {
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();

        lqw.eq(dto.getStatus() != null, ApUserRealname::getStatus, dto.getStatus());

        page(page, lqw);

        PageResultVo<ApUserRealname> result = PageResultVo.pageResult(page.getPages(), page.getSize(), page.getTotal(), page.getRecords());

        return result;
    }

    /**
     * 审核 — 通过
     *
     * @param paramMap
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void authPass(Map<String, Object> paramMap) {
        //1.获取参数
        Long id = (Long) paramMap.get("id");
        log.debug("实名认证：id={}", id);
        if (id == null) {
            //抛出异常错误提示：缺少参数   PARAM_REQUIRE：缺少参数
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        //2.构建对象
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(id);
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        apUserRealname.setUpdatedTime(LocalDateTime.now());

        updateById(apUserRealname);

        ApUserRealname realname = getById(id);

        if (realname == null) {
            //抛出异常错误消息：数据不存在
            throw new LeadNewsException(HttpCodeEnum.DATA_NOT_EXIST);
        }

        Long userId = realname.getUserId();

        ApUser apUser = new ApUser();

        apUser.setId(userId);
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);

        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_PERSONAL);

        apUserMapper.updateById(apUser);

        log.debug("实名认证 从普通用户升级为自媒体人：id={}, UserId={}", id, userId);

        ApUser appUserInfo = apUserMapper.selectById(userId);
        Long wmUserId = addWmUser(userId, appUserInfo);
        log.debug("实名认证 添加自媒体账号成功：id={}, appUserId={}, wmUserId={}", id, userId,wmUserId);
        //TODO 5. 远程调用创建(文章微服务)作者账号
        addApAuthor(wmUserId, appUserInfo);
        log.debug("实名认证 添加作者账号成功：id={},userId={},wmUserId={]", id, userId, wmUserId);

    }

    /**
     * 审核 — 驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //1.获取参数
        Long id = (Long) paramMap.get("id");
        String msg = (String) paramMap.get("msg");
        //2.构建新对象
        ApUserRealname pojo = new ApUserRealname();

        pojo.setReason(msg);
        pojo.setId(id);
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        pojo.setUpdatedTime(LocalDateTime.now());
        //3.做更新操作
        updateById(pojo);
    }


    /**
     * 添加作者信息
     * @param wmUserId
     * @param appUserInfo
     */
    private void addApAuthor(Long wmUserId, ApUser appUserInfo) {

        ResultVo<ApAuthor> getResult = apauthorFeign.getByApUserAndWmUserId(appUserInfo.getId(), wmUserId);

        if (!getResult.isSuccess()){
            throw new LeadNewsException("调用文章微服务 查询作者信息失败！");
        }

        ApAuthor author = getResult.getData();

        if (null != author){
            author = new ApAuthor();

            author.setName(appUserInfo.getName());
            author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            author.setUserId(appUserInfo.getId());
            author.setWmUserId(wmUserId);
            author.setCreatedTime(LocalDateTime.now());

            ResultVo resultVo = apauthorFeign.addApAuthor(author);

            if (!resultVo.isSuccess()){
                throw new LeadNewsException("调用微服务 添加作者信息失败！");
            }
        }
    }



    private Long addWmUser(Long appUserId, ApUser appUserInfo){

        ResultVo<WmUser> wmUserResult = wmUserFeign.getByApUserId(appUserId);
        if (wmUserResult.isSuccess()){
            throw new LeadNewsException("调取自媒体微服务失败");
        }
        WmUser wmUser = wmUserResult.getData();

        if (null != wmUser){
            wmUser = new WmUser();

            BeanUtils.copyProperties(appUserInfo,wmUser);

            wmUser.setId(null);
            wmUser.setApUserId(appUserId);
            wmUser.setNickname(appUserInfo.getName());
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setCreatedTime(LocalDateTime.now());
            ResultVo<WmUser> insertResult = wmUserFeign.addWmUser(wmUser);

            if (!insertResult.isSuccess()){
                throw new LeadNewsException("调用自媒体微服务添加账号失败！");
            }
            wmUser  = insertResult.getData();
        }
        return wmUser.getId();
    }


}
